package com.ddxcloud.movie.controller;

import cn.hutool.core.util.ObjectUtil;
import com.ddxcloud.common.constants.enums.ResultCodeEnum;
import com.ddxcloud.common.utils.Result;
import com.ddxcloud.movie.dto.WxLoginDTO;
import com.ddxcloud.movie.entity.User;
import com.ddxcloud.movie.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;

@RestController
@RequestMapping("/login")
@Api(tags = "登录")
public class LoginController {

    @Resource
    UserService userService;

    /**
     * 微信登录
     * @param dto
     * @param bindingResult
     * @return
     * @throws WxErrorException
     */
    @Operation(summary = "微信登录")
    @PostMapping(value = "/loginByWechat")
    public Result<User> loginByWechat(@Validated @RequestBody WxLoginDTO dto, BindingResult bindingResult) throws WxErrorException {
        if (bindingResult.hasErrors()) {
            String errorMsg = Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage();
            return Result.fail(errorMsg);
        }
        User user = userService.loginByWechat(dto);
        if (ObjectUtil.isNotEmpty(user)) {
            return Result.success(user);
        }
        return Result.fail(ResultCodeEnum.LOGIN_ERROR.getMsg(), ResultCodeEnum.LOGIN_ERROR);
    }
}
